<?php

use common\models\c2\entity\Product;
use unclead\multipleinput\MultipleInput;
use yii\helpers\Html;
use kartik\widgets\ActiveForm;
use kartik\builder\Form;
use kzo\base\models\statics\EntityModelStatus;
use kzo\base\widgets\ui\bs4\Alert;
use yii\helpers\Url;

/* @var $model common\models\c2\entity\InventoryDeliveryNote */

$regularLangName = \Yii::$app->kzoHelper->getRegularLangName();
$messageName = $model->getMessageName();
?>

<?php
$form = ActiveForm::begin([
    'action' => ['edit', 'id' => $model->id],
    'options' => [
        'id' => $model->getBaseFormName(),
        'data-pjax' => true,
    ]]);
?>

    <div class="<?= $model->getPrefixName('form') ?> card bg-light mt-2">
        <div class="card-body">

            <?php if (Yii::$app->session->hasFlash($messageName)): ?>
                <?php if (!$model->hasErrors()) {
                    echo Alert::widget([
                        'type' => Alert::TYPE_SUCCESS,
                        'title' => 'Well Down',
                        'icon' => 'fas fa-ok-circle',
                        'body' => Yii::$app->session->getFlash($messageName),
                        'showSeparator' => true,
                        'delay' => 2000
                    ]);
                } else {
                    echo Alert::widget([
                        'type' => Alert::TYPE_WARNING,
                        'title' => 'Warning!',
                        'icon' => 'fas fa-ok-circle',
                        'body' => Yii::$app->session->getFlash($messageName),
                        'showSeparator' => true,
                    ]);
                }
                ?>
            <?php endif; ?>

            <?php
            echo Form::widget([
                'model' => $model,
                'form' => $form,
                'columns' => 6,
                'attributes' => [
                    // 'type' => ['type' => Form::INPUT_DROPDOWN_LIST, 'items' => []],
                    'code' => ['type' => Form::INPUT_TEXT, 'options' => ['placeholder' => $model->getAttributeLabel('code')]],
                    'warehouse_id' => [
                        'type' => Form::INPUT_DROPDOWN_LIST,
                        'items' => \common\models\c2\entity\Warehouse::getHashMap('id', 'name', ['status' => EntityModelStatus::STATUS_ACTIVE]),
                        'options' => [
                            'placeholder' => $model->getAttributeLabel('warehouse_id')
                        ]
                    ],
                    'grand_total' => ['type' => Form::INPUT_TEXT, 'options' => ['placeholder' => $model->getAttributeLabel('grand_total')]],
                    'payment_method' => ['type' => Form::INPUT_TEXT, 'options' => ['placeholder' => $model->getAttributeLabel('payment_method')]],
                    'delivery_method' => ['type' => Form::INPUT_TEXT, 'options' => ['placeholder' => $model->getAttributeLabel('delivery_method')]],

                    'occurrence_date' => ['type' => Form::INPUT_WIDGET, 'widgetClass' => '\kartik\widgets\DateTimePicker', 'options' => [
                        'options' => ['placeholder' => Yii::t('app.c2', 'Date Time...')], 'pluginOptions' => ['format' => 'yyyy-mm-dd hh:ii:ss', 'autoclose' => true],
                    ],],
                    // 'contact_man' => ['type' => Form::INPUT_TEXT, 'options' => ['placeholder' => $model->getAttributeLabel('contact_man')]],
                    // 'cs_name' => ['type' => Form::INPUT_TEXT, 'options' => ['placeholder' => $model->getAttributeLabel('cs_name')]],
                    // 'sender_name' => ['type' => Form::INPUT_TEXT, 'options' => ['placeholder' => $model->getAttributeLabel('sender_name')]],
                    // 'financial_name' => ['type' => Form::INPUT_TEXT, 'options' => ['placeholder' => $model->getAttributeLabel('financial_name')]],


                    // 'remote_ip' => ['type' => Form::INPUT_TEXT, 'options' => ['placeholder' => $model->getAttributeLabel('remote_ip')]],
                    // 'state' => ['type' => Form::INPUT_WIDGET, 'widgetClass' => '\kartik\checkbox\CheckboxX', 'options' => [
                    //     'pluginOptions' => ['threeState' => false],
                    // ],],
                    'status' => ['type' => Form::INPUT_DROPDOWN_LIST, 'items' => EntityModelStatus::getHashMap('id', 'label')],
                    // 'position' => ['type' => Form::INPUT_WIDGET, 'widgetClass' => '\kartik\touchspin\TouchSpin',],
                ]]);

            echo Form::widget([
                'model' => $model,
                'form' => $form,
                'columns' => 6,
                'attributes' => [
                    'customer_id' => [
                        'type' => Form::INPUT_WIDGET,
                        'widgetClass' => \kartik\select2\Select2::className(),

                        'options' => [
                            'data' => ['' => 'selecting...'] + \common\models\c2\entity\FeUser::getHashMap('id', 'username', [
                                    'status' => EntityModelStatus::STATUS_ACTIVE,
                                    'type' => \common\models\c2\statics\FeUserType::TYPE_CUSTOMER
                                ]),
                            'pluginEvents' => [
                                'change' => "function(){
                                    $.post('" . Url::toRoute(['sales-orders']) . "', {'depdrop_all_params[customer_id]':$(this).val(),'depdrop_parents[]':$(this).val()}, function(data){
                                    if(data.output !== undefined){
                                        $('select#order-list').empty();
                                        $.each(data.output, function(key, item){
                                            $('select#order-list').append('<option value=' + item.id + '>' + item.code + '</option>');
                                        });
                                        $('#address').val(data.profile.address);
                                    }
                                });}"
                            ],
                        ]
                    ],
                    'sales_order_id' => [
                        'type' => Form::INPUT_DROPDOWN_LIST,
                        'items' => $model->isNewRecord ? [] : $model->customer->getSalesOrderOptions('id', 'code', [
                            // 'state' => \common\models\c2\statics\SalesOrderState::FINISH
                        ]),
                        'options' => [
                            'id' => 'order-list',
                            'placeholder' => $model->getAttributeLabel('sales_order_id')
                        ]
                    ],
                    'label' => [
                        'type' => Form::INPUT_TEXT,
                        'label' => Yii::t('app.c2', 'Address'),
                        'options' => [
                            'id' => 'address',
                            'placeholder' => $model->getAttributeLabel('label')
                        ]
                    ],

                ]
            ]);


            echo Form::widget([
                'model' => $model,
                'form' => $form,
                'attributes' => [
                    'memo' => ['type' => Form::INPUT_WIDGET, 'widgetClass' => '\vova07\imperavi\Widget', 'options' => [
                        'settings' => [
                            'minHeight' => 150,
                            'buttonSource' => true,
                            'lang' => $regularLangName,
                            'plugins' => [
                                'fontsize',
                                'fontfamily',
                                'fontcolor',
                                'table',
                                'textdirection',
                                'fullscreen',
                            ],
                        ]
                    ],],
                ]
            ]);

            $multipleItemsId = $model->getPrefixName('items');
            echo Form::widget([
                'model' => $model,
                'form' => $form,
                'columns' => 1,
                'attributes' => [
                    'items' => [
                        'type' => Form::INPUT_WIDGET,
                        'widgetClass' => unclead\multipleinput\MultipleInput::className(),
                        'options' => [
                            'id' => $multipleItemsId,
                            'data' => $model->items,
                            //                        'max' => 4,
                            'allowEmptyList' => true,
                            'rowOptions' => function ($model, $index, $context) use ($multipleItemsId) {
                                return ['id' => "row{multiple_index_{$multipleItemsId}}", 'data-id' => $model['id']];
                            },
                            'addButtonOptions' => [
                                'class' => 'btn btn-success',
                                'label' => Html::tag('i', null, ['class' => 'fa fa-plus'])
                            ],
                            'removeButtonOptions' => [
                                'class' => 'btn btn-danger',
                                'label' => Html::tag('i', null, ['class' => 'fa fa-minus'])
                            ],
                            'columns' => [
                                [
                                    'name' => 'id',
                                    'type' => 'hiddenInput',
                                ],
                                [
                                    'name' => 'product_id',
                                    'type' => \kartik\widgets\Select2::className(),
                                    'title' => Yii::t('app.c2', 'Product'),
                                    'enableError' => true,
                                    'headerOptions' => ['style' => 'width: 200px',],
                                    // 'items' => ['' => Yii::t("app.c2", "Select...")] + Product::getHashMap('id', 'name', ['status' => EntityModelStatus::STATUS_ACTIVE]),
                                    'options' => [
                                        'data' => ['' => Yii::t("app.c2", "Select...")] + Product::getHashMap('id', 'name', [
                                                'status' => EntityModelStatus::STATUS_ACTIVE
                                            ]),
                                        'pluginEvents' => [
                                            'change' => "function() {
                                                $.post('" . Url::toRoute(['skus']) . "', {'depdrop_all_params[product_id]':$(this).val(),'depdrop_parents[]':$(this).val()}, function(data){
                                                    if(data.output !== undefined){
                                                        $('select#subcat-{multiple_index_{$multipleItemsId}}').empty();
                                                        $.each(data.output, function(key, item){
                                                            $('select#subcat-{multiple_index_{$multipleItemsId}}').append('<option value=' + item.id + '>' + item.name + '</option>');
                                                        });
                                                    }
                                                    if(data.packages !== undefined){
                                                        $('select#package-{multiple_index_{$multipleItemsId}}').empty();
                                                        $.each(data.packages, function(key, item){
                                                            $('select#package-{multiple_index_{$multipleItemsId}}').append('<option value=' + item.id + '>' + item.name + '</option>');
                                                        });
                                                    }
                                                });
                                            }",
                                        ],
                                    ],
                                ],
                                [
                                    'name' => 'product_sku_id',
                                    'type' => 'dropDownList',
                                    'title' => Yii::t('app.c2', 'Product Sku'),
                                    'enableError' => true,
                                    'headerOptions' => ['style' => 'width: 200px',],
                                    'items' => $model->isNewRecord ? [] : function ($data) {
                                        if (is_object($data)) {
                                            return $data->product->getProductSkuOptionsList();
                                        }
                                        return [];
                                    },
                                    'options' => [
                                        'id' => "subcat-{multiple_index_{$multipleItemsId}}",
                                    ],
                                ],
                                [
                                    'name' => 'package_id',
                                    'type' => 'dropDownList',
                                    'title' => Yii::t('app.c2', 'Product Package'),
                                    'enableError' => true,
                                    'headerOptions' => ['style' => 'width: 200px',],
                                    'items' => $model->isNewRecord ? [] : function ($data) {
                                        if (is_object($data)) {
                                            return $data->product->getProductPackageOptionsList();
                                        }
                                        return [];
                                    },
                                    'options' => [
                                        'id' => "package-{multiple_index_{$multipleItemsId}}",
                                    ],
                                ],
                                [
                                    'name' => 'measure_id',
                                    'title' => Yii::t('app.c2', 'Measure'),
                                    'type' => 'dropDownList',
                                    'headerOptions' => ['style' => 'width: 90px',],
                                    'enableError' => true,
                                    'items' => \common\models\c2\entity\Measure::getHashMap('id', 'label'),
                                ],
                                [
                                    'name' => 'pieces',
                                    // 'type' => kartik\widgets\TouchSpin::className(),
                                    'title' => Yii::t('app.c2', 'Pieces'),
                                    'defaultValue' => 1,
                                    'options' => [

                                    ]
                                ],
                                [
                                    'name' => 'price',
                                    // 'type' => kartik\widgets\TouchSpin::className(),
                                    'title' => Yii::t('app.c2', 'Price'),
                                    'defaultValue' => 0.000,
                                    'options' => [
                                        'type' => 'number',
                                        'step' => 0.001
                                    ]
                                ],
                                [
                                    'name' => 'quantity',
                                    // 'type' => kartik\widgets\TouchSpin::className(),
                                    'title' => Yii::t('app.c2', 'Quantity'),
                                    'defaultValue' => 0,
                                    'options' => [
                                        'pluginOptions' => [
                                            // 'buttondown_txt' => '<i class="glyphicon glyphicon-minus-sign"></i>',
                                            // 'buttonup_txt' => '<i class="glyphicon glyphicon-plus-sign"></i>',
                                        ],
                                    ]
                                ],
                                [
                                    'name' => 'subtotal',
                                    'title' => Yii::t('app.c2', 'Subtotal'),
                                    'enableError' => true,
                                    'options' => [
                                        'type' => 'number',
                                        'pluginOptions' => [
                                        ],
                                    ]
                                ],
                                // [
                                //     'name' => 'send_pieces',
                                //     // 'type' => kartik\widgets\TouchSpin::className(),
                                //     'title' => Yii::t('app.c2', 'Send Pieces'),
                                //     'defaultValue' => 1,
                                //     'options' => [
                                //         'pluginOptions' => [
                                //         ],
                                //     ]
                                // ],
                                [
                                    'name' => 'memo',
                                    'title' => Yii::t('app.c2', 'Memo'),
                                    'enableError' => true,
                                ],
                            ]
                        ],
                    ],
                ]
            ]);

            echo Html::submitButton('<i class="fa fa-save"></i> ' . Yii::t('app.c2', 'Save'), ['type' => 'button', 'class' => 'btn btn-primary float-right ml-2']);
            echo Html::a('<i class="fa fa-arrow-left"></i> ' . Yii::t('app.c2', 'Go Back'), ['index'], ['data-pjax' => '0', 'class' => 'btn btn-light float-right', 'title' => Yii::t('app.c2', 'Go Back'),]);
            ?>

        </div>
    </div>
<?php ActiveForm::end(); ?>
<?php
$js = "";
$js .= "jQuery('.btn.multiple-input-list__btn.js-input-remove').off('click').on('click', function(){
    var itemId = $(this).closest('tr').data('id');
    if(itemId){
       $.ajax({url:'" . Url::toRoute('delete-subitem') . "',data:{id:itemId}}).done(function(result){;}).fail(function(result){alert(result);});
    }
});\n";
$this->registerJs($js);
?>